package cn.edu.sdjzu.knoverse.utils.login;

import cn.edu.sdjzu.knoverse.utils.exception.CustomException;
import cn.edu.sdjzu.knoverse.model.dto.system.user.LoginDto;
import cn.edu.sdjzu.knoverse.model.entity.system.User;
import cn.edu.sdjzu.knoverse.model.vo.result.ResultCodeEnum;

import java.util.Map;

/**
 * 登录策略上下文
 */
public class LoginContext {
    private final Map<String, LoginStrategy> strategies;

    public LoginContext(Map<String, LoginStrategy> strategies) {
        this.strategies = strategies;
    }

    /**
     * 执行登录策略
     * 根据情况判断 type 是否为空
     *
     * @param loginDto 登录参数
     * @return 用户
     */
    public User executeStrategy(LoginDto loginDto) {
        String type = loginDto.getType();
        LoginStrategy strategy = strategies.get(type);
        if (strategy == null) {
            throw new CustomException(ResultCodeEnum.SERVICE_ERROR);
        }
        return strategy.authenticate(loginDto);
    }
}